#!/usr/bin/python
# coding: iso-8859-15

'''haclient.py, the GUI manamgement tool for Linux-HA'''
import sys, os, string, socket, syslog, webbrowser, pickle, xml, gc, time, binascii, thread, tarfile, tempfile
from stat import *
from xml.dom.minidom import parseString
from xml.dom.minidom import getDOMImplementation
import re
import pdb
import locale, gettext
app_name = "haclient"

sys.path.append("@HA_DATADIR@/heartbeat-gui")
sys.path.append("@LIBDIR@/heartbeat-gui")

from nkha_constants import *
__authors__ = AUTHORS
__license__ = GPLV2PLUS
from license_register import HALicenseManager, HALic_ctrl_IS_flag
from basefunc import confirmbox, msgbox

from IS_Scrolled import *

from IPy import IP
from pymgmt import *

import pygtk
pygtk.require('2.0')
import gtk, gobject, gtk.glade
import datetime
class switchview:
        def get_database(self):
		flag=self.manager.do_cmd_twice("get_sqldata\n%s\n%s"%("", str("SELECT flag,flag_mail from is_flag;")))

		if self.manager.failed_reason != "" or flag == None or flag == []:
	                self.is_switch="off"
        	        self.is_warn="off"
		else:
                	self.is_switch=flag[0].split('|')[0]
	                self.is_warn=flag[0].split('|')[1]

		mails=self.manager.do_cmd_twice("get_sqldata\n%s\n%s"%("", str("SELECT time,type,stat,recv,data from is_mail;")))

                self.warn_list=[]
		if self.manager.failed_reason == "" and mails != None and mails != []:
	                for item in mails:
        	                mail_item={}
                	        mail=item.split('|')
                        	mail_item['time']=mail[0]
	                        mail_item['type']=mail[1]
        	                mail_item['stat']=mail[2]
                	        mail_item['recv']=mail[3]
                        	mail_item['data']=mail[4]
	                        self.warn_list.append(mail_item)

		self.num_warn_list = len(self.warn_list)
                if self.num_warn_list > 0:
                	self.warn_list=self.warn_list[::-1]
                self.update_data()

		return True


	def page_button_sensitive(self):
                self.page_sum()
                self.widget_pagenum.set_text(_("page num %d")%self.pagenum)
                if self.pagenum == 1:
                       self.widget_pageup.set_sensitive(False)
                       self.widget_firstpage.set_sensitive(False)
                else:
                       self.widget_pageup.set_sensitive(True)
                       self.widget_firstpage.set_sensitive(True)
                if self.pagenum == self.pasum:
                       self.widget_pagedown.set_sensitive(False)
                       self.widget_lastpage.set_sensitive(False)
                else:
                       self.widget_pagedown.set_sensitive(True)
                       self.widget_lastpage.set_sensitive(True)

                return

	def update_table(self):
		self.alarm_table = gtk.Table(1, self.columns_num, False)
		self.alarm_table.set_row_spacings(10)
		self.alarm_table.set_col_spacings(3)
		for i in range(self.columns_num):
			
			label = gtk.Label()
			label.set_markup(_(self.alarm_titles[i]))
			#label.set_markup('<span foreground="blue"><u>'+_(self.alarm_titles[i])+'</u></span>')
			aligned_label = gtk.Alignment(0.5, 0.5, 0, 0)
			box = gtk.HBox(True, 0)
			box.pack_start(aligned_label, False, False, 0)
			#label.set_alignment(0.5, 0.5)
			aligned_label.show()
                	aligned_label.add(label)

			frame = gtk.Frame()
			frame.set_shadow_type(gtk.SHADOW_IN)
			frame.add(box)

			self.alarm_table.attach(frame, i, i+1, 0, 1,gtk.FILL|gtk.EXPAND,gtk.SHRINK)
		if self.viewport != '':
			self.viewport.destroy()
		self.viewport = gtk.Viewport()
		self.viewport.add(self.alarm_table)
		
		self.alarm_window.add(self.viewport)
		return

	def update_label(self, mail_item):
		for i in range(self.columns_num):
			
			label = gtk.Label(mail_item[self.alarm_titles[i]])
			if mail_item[self.alarm_titles[i]] == 'FAILED':
				label.set_markup('<span foreground="red">'+mail_item[self.alarm_titles[i]]+'</span>')
			aligned_label = gtk.Alignment(0.5, 0.5, 0, 0)
			box = gtk.HBox(True, 0)
			box.pack_start(aligned_label, False, False, 0)
			aligned_label.show()
                	aligned_label.add(label)
			self.alarm_table.attach(box, i, i+1, self.num_warn, self.num_warn+1, gtk.FILL|gtk.EXPAND, gtk.SHRINK)
		self.num_warn +=1
		separator = gtk.HSeparator()
        	self.alarm_table.attach(separator, 0, self.columns_num, self.num_warn, self.num_warn+1, gtk.FILL|gtk.EXPAND, gtk.SHRINK)
		self.num_warn +=1
		return
	
	def update_data(self):
		self.update_table()
		if self.num_warn_list > 0:
                        self.page_button_sensitive()
                        self.num_warn = 1
                        if self.num_warn_list > 10:
                                for mail_item in self.warn_list[10*(self.pagenum - 1):10*self.pagenum]:
					self.update_label(mail_item)
                        else:
				
                                for mail_item in self.warn_list:
					self.update_label(mail_item)

                self.num_warn = 1
		self.alarm_window.show_all()
                return True

 	def on_alarm(self):
		self.xml_isalarm = self.manager.xml_nodes["cib"].getElementsByTagName("alarmd")[0]
		try:	
			self.xml_ismail = self.xml_isalarm.getElementsByTagName("mail")[0]
			return 0 			
		except:
			ret = confirmbox(top_window, _("If you want to use intellect alarm,please configure the mail alarm!")+"\n"+_("Configure it now?"),
                                (gtk.STOCK_NO, gtk.RESPONSE_NO,
                                 gtk.STOCK_YES, gtk.RESPONSE_YES))
			if ret == gtk.RESPONSE_YES :
				alarmview()
				is_alarm = self.manager.xml_nodes["cib"].getElementsByTagName("alarmd")[0]
      				try:
					is_mail = is_alarm.getElementsByTagName("mail")[0]
					return 0
				except:
					return 1 
			else:
				return 1
		
	def page_sum(self):
		self.pasum = self.num_warn_list // 10
                if (self.num_warn_list % 10 != 0):
                        self.pasum = self.pasum + 1
                self.widget_pagesum.set_text(_("page sum %d")%self.pasum)
                return

	def update(self):
		if self.is_switch == "on":
                        self.widget_ISbutton.set_active(True)
                else:
                        self.widget_ISbutton.set_active(False)

		self.ISbutton_callback(self.widget_ISbutton)
	
                if self.is_warn == "on":
                        self.widget_prebutton.set_active(True)
                        self.widget_prebutton_image.set_from_stock(gtk.STOCK_YES, gtk.ICON_SIZE_BUTTON)
			if self.timer == -1:
                        	self.timer = gobject.timeout_add_seconds(180, self.get_database)
			self.widget_prebutton.set_tooltip_text(_(self.label_warn_on_text))
                else:
                        self.widget_prebutton.set_active(False)
                        self.widget_prebutton_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
			self.widget_prebutton.set_tooltip_text(_(self.label_warn_off_text))
	#	self.prewarnbutton_callback(self.widget_prebutton)

		if self.num_warn_list == 0:
                        self.pagenum = 1
                        self.widget_pagenum.set_text('')
                        self.widget_pagesum.set_text('')
                        self.widget_pageup.set_sensitive(False)
                        self.widget_pagedown.set_sensitive(False)
                        self.widget_firstpage.set_sensitive(False)
                        self.widget_lastpage.set_sensitive(False)
                else:
			self.page_button_sensitive()

                return True

	def ISbutton_callback(self,widget,data=None):
                self.is_button = ("off", "on")[widget.get_active()]
		label_on_text="The IS is on.You can press the button to turn it off."  
		label_off_text="The IS is off.You can press the button to turn it on."
                if self.is_button == "on":
                        self.widget_ISbutton_image.set_from_stock(gtk.STOCK_YES, gtk.ICON_SIZE_BUTTON)
			self.widget_ISbutton.set_tooltip_text(_(label_on_text))
                else:
                        self.widget_ISbutton_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
			self.widget_ISbutton.set_tooltip_text(_(label_off_text))
                return

	def prewarnbutton_callback(self,widget,data=None):
                self.is_warn_button = ("off", "on")[widget.get_active()]
                if self.is_warn_button == "on":
			if self.on_alarm() == 0:
                        	self.widget_prebutton_image.set_from_stock(gtk.STOCK_YES, gtk.ICON_SIZE_BUTTON)
				if self.timer == -1:
                        		self.timer = gobject.timeout_add_seconds(180, self.get_database)
				self.widget_prebutton.set_tooltip_text(_(self.label_warn_on_text))
			else:
				self.widget_prebutton.set_active(False)
                else:
                        self.widget_prebutton_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
                        gobject.source_remove(self.timer)
			self.timer = -1
			self.widget_prebutton.set_tooltip_text(_(self.label_warn_off_text))
		self.is_prewarn_button = ("off", "on")[self.widget_prebutton.get_active()]
		self.manager.update_database("update is_flag set flag_mail='%s';"%(str(self.is_prewarn_button)))
                return

        def IS_mailrefresh(self,widget):
                self.get_database()
                self.update()
                return

	def page_turning(self, widget):
                if widget.get_name() == "pagedown":
                        self.pagenum = self.pagenum + 1
                if widget.get_name() == "pageup":
                        self.pagenum = self.pagenum - 1
                if widget.get_name() == "firstpage":
                        self.pagenum = 1
                if widget.get_name() == "lastpage":
                        self.pagenum = self.pasum
		
		#self.viewport.destroy()
                self.update_data()
                return

	def expanded_cp(self, widget, params):
		page = self.widget_notebook.get_current_page()
		if self.widget_IS.get_expanded() and page != 0:
			 self.widget_notebook.set_current_page(0)
		if self.widget_prewarning.get_expanded() and page !=1:
			 self.widget_notebook.set_current_page(1)
		return

        def __init__(self, top_window, manager):
		self.manager = manager
                dialog = gtk.Dialog(_("Intellect Switch&Alarm Configuration"), top_window, gtk.DIALOG_MODAL,
                                      (gtk.STOCK_QUIT, gtk.RESPONSE_CANCEL))
                #dialog.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_NORMAL)

                dialog.show_all()
                dialog.set_position(gtk.WIN_POS_CENTER_ALWAYS)
                glade = gtk.glade.XML(UI_FILE, "notebook_is", "haclient")
                layout = glade.get_widget("notebook_is")
                dialog.vbox.add(layout)
		

		self.widget_notebook = glade.get_widget("notebook_is")
		
		self.widget_IS = glade.get_widget("expander_is")
		self.widget_IS.set_expanded(True)
		self.widget_IS.connect('notify::expanded', self.expanded_cp)
		self.widget_ISbutton = glade.get_widget("isbutton")
		self.widget_ISrefresh = glade.get_widget("is_refresh")
		self.widget_ISbutton_image = glade.get_widget("isbutton_image")
		self.widget_ISframe = glade.get_widget("ISframe")
		self.widget_prewarning = glade.get_widget("expander_alarm")
		self.widget_prewarning.set_expanded(True)
		self.widget_prewarning.connect('notify::expanded', self.expanded_cp)
                self.widget_prebutton = glade.get_widget("prebutton")
 		self.widget_prebutton.connect('released', self.prewarnbutton_callback)
		self.widget_prebutton_image = glade.get_widget("prebutton_image")

		self.alarm_window = glade.get_widget("alarm_scrolledwindow")
		self.alarm_window.set_shadow_type(gtk.SHADOW_IN)
		self.alarm_window.set_border_width(5)
		self.alarm_window.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_ALWAYS)
  	
		self.alarm_frame = glade.get_widget("alarmframe")	
                self.alarm_titles = ['time', 'type', 'stat', 'recv', 'data'] 
		self.columns_num = len(self.alarm_titles)

		self.widget_pagenum = glade.get_widget("pagenum")
                self.widget_pagesum = glade.get_widget("pagesum")
                self.widget_pageup = glade.get_widget("pageup")
		self.widget_pageup.set_tooltip_text(_("previous page"))
                self.widget_pagedown = glade.get_widget("pagedown")
		self.widget_pagedown.set_tooltip_text(_("next page"))

		self.widget_firstpage = glade.get_widget("firstpage")
		self.widget_firstpage.set_tooltip_text(_("to the first page"))
                self.widget_lastpage = glade.get_widget("lastpage")
		self.widget_lastpage.set_tooltip_text(_("to the last page"))
                self.widget_refresh = glade.get_widget("refresh")
		self.widget_refresh.set_tooltip_text(_("refresh the IS alarm mail list"))

                glade.get_widget('firstpage').connect('clicked', self.page_turning)
                glade.get_widget('pageup').connect('clicked', self.page_turning)
                glade.get_widget('pagedown').connect('clicked', self.page_turning)
		glade.get_widget('refresh').connect('clicked', self.IS_mailrefresh)
                glade.get_widget('lastpage').connect('clicked', self.page_turning)

	#	self.switchtips = gtk.Tooltips()
		self.label_warn_on_text="The alarm is on.You can press the button to turn it off."  
		self.label_warn_off_text="The alarm is off.You can press the button to turn it on."
		self.viewport = ''
                self.pagenum = 1
                self.timer = -1			

                self.get_database()
		self.update()

		is_scrolled = IS_Scrolled(self.manager, self.widget_ISbutton,
			self.widget_ISbutton_image, self.widget_ISrefresh,
			self.widget_ISframe, dialog, 
			self.widget_prebutton, self.widget_prebutton_image)
		self.widget_ISframe.show_all()
		self.alarm_window.show_all()

                save_top_window = top_window
                top_window = dialog
                while True :
                        ret = dialog.run()
                        if ret in [gtk.RESPONSE_CANCEL, gtk.RESPONSE_DELETE_EVENT]:
                                if self.timer != -1:
                                        gobject.source_remove(self.timer)
				if is_scrolled.timer != -1:
					gobject.source_remove(is_scrolled.timer)
                                dialog.destroy()
                                top_window = save_top_window
                                return None
                return

